import { fetchPostData, fetchGetData } from '@/api/fetch'
import { setToken, getToken, setCookie, getCookie, getFormParams } from '@/libs/util'

export default {
    changeCityAct(ctx, city) {
        ctx.commit('setCity', city)
        // localStorage.setItem('city', city.name);
    },
    // 登录
    handleLogin({ commit }, { nickName, pwd }) {
        let userName = nickName.trim()
        let password = pwd.trim()
        return new Promise((resolve, reject) => {
            fetchPostData('/api/user/login', getFormParams({ nickName: userName, pwd: password }))
                .then(res => {
                    if (res.status == 1) {
                        console.log("登录成功")
                        const data = res.data;
                        commit('setToken', data.token);
                        commit('setUser', data.userInfo);
                        try {
                            localStorage.setItem('userId', data.userInfo.id);
                        } catch (error) {
                            console.log("localStorage fail!")
                        }
                        resolve()
                    } else {
                        reject(res.message)
                    }
                })
        })
    },
    // 退出登录
    handleLogOut({ state, commit }) {
        return new Promise((resolve, reject) => {
            commit('setToken', '');
            localStorage.userId = "";
            commit('setUser', '');
            resolve();
        })
    },
    
}